import React, { useEffect, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { Field, Button, Form, Input, Toast } from "react-vant";
import { ArrowLeft, Ellipsis } from '@react-vant/icons';
import TopTitleBar from "../../components/TopTitleBar";
import axios from "../../utils/axios";
import "./index.css";
import { data } from "browserslist";
import { myContext } from "../../context";
const AccountManagement = () => {
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const { userInfos, updateUserInfo } = useContext(myContext);
    // 先 ajax 获取 accountInfos， set 成功之后，渲染页面！

    useEffect(() => {
        // 为什么 从个人中心过来的时候，会说： 未登录？？
        // 为什么 只有这一个没有更新？？？
        form.setFieldsValue(userInfos);
    })
    const onFinish = val => {
        axios.put('/api/v1/user/info', data = {
            nickName: val.nickName,
            introduceSign: val.introduceSign
        }).then(res => {
            if(res.data.resultCode === 200) {
                Toast.success('修改成功');
                updateUserInfo(val);
            }
        })
    }
    const loginOut = () => {
        axios.post('/api/v1/user/logout').then(res => {
            if (res.data.message === 'SUCCESS') {
                // 清除 token 
                // 并且 默认 跳转到 login 页面！
                localStorage.removeItem('Token');
                navigate('/login');
            }
        })
    }
    return (
        <Form className="accountManagement"
            form={form}
            onFinish={onFinish}
        >
            <TopTitleBar
                leftIcon={
                    <ArrowLeft onClick={() => navigate(-1)} />
                }
                intermediateContentText="账号管理"
                rightIcon={
                    <Ellipsis />
                }
            />
            <div className="mainContent">
                {/* 写一个组件，或者 用 vant 组件： */}
                <Form.Item
                    label='昵称'
                    name='nickName'
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label='个性签名'
                    name='introduceSign'
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label='修改密码'
                    name='changePassword'
                >
                    <Input />
                </Form.Item>

                <Button className="loginButton" color="#1baeae" text='保存' nativeType="submit" />
                <Button className="loginButton" color="#1baeae" text='退出登录' onClick={loginOut} />
            </div>
        </Form>
    )
};

export default AccountManagement;
